package com.zmx.core.client.auth;

import com.zmx.core.config.MarshallingCodeCFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 客户端实例
 * @ClassName: Client
 * @Author zhaomxr
 * @Date 2021-12-14 15:21
 */
@Slf4j
public class Client {

    public void start(int port, String username, String password, String secret, String authUrl, int authRetryTime, int authHeartRetryTime) {

        try {
            EventLoopGroup group = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();

            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                            sc.pipeline().addLast(new ClientHandler(port, username, password, secret, authUrl, authRetryTime, authHeartRetryTime));
                        }
                    });

            String[] ipAndPort = authUrl.split(":");
            ChannelFuture cf = b.connect(ipAndPort[0], Integer.valueOf(ipAndPort[1])).sync();

            cf.channel().closeFuture().sync();
            group.shutdownGracefully();
        } catch (InterruptedException e) {
            log.info("register to server {} fail!", authUrl);
        }
    }
}
